home *** CD-ROM | disk | FTP | other *** search
/ Freelog 115 / FreelogNo115-MaiJuin2013.iso / Internet / Filezilla Server / FileZilla_Server-0_9_41.exe / source / misc / mmgr.cpp < prev    next >
C/C++ Source or Header  |  2011-11-06  |  76KB  |  1,887 lines

  1. // ---------------------------------------------------------------------------------------------------------------------------------
  2. //                                                      
  3. //                                                      
  4. //  _ __ ___  _ __ ___   __ _ _ __      ___ _ __  _ __  
  5. // | '_ ` _ \| '_ ` _ \ / _` | '__|    / __| '_ \| '_ \ 
  6. // | | | | | | | | | | | (_| | |    _ | (__| |_) | |_) |
  7. // |_| |_| |_|_| |_| |_|\__, |_|   (_) \___| .__/| .__/ 
  8. //                       __/ |             | |   | |    
  9. //                      |___/              |_|   |_|    
  10. //
  11. // Memory manager & tracking software
  12. //
  13. // Best viewed with 8-character tabs and (at least) 132 columns
  14. //
  15. // ---------------------------------------------------------------------------------------------------------------------------------
  16. //
  17. // Restrictions & freedoms pertaining to usage and redistribution of this software:
  18. //
  19. //  * This software is 100% free
  20. //  * If you use this software (in part or in whole) you must credit the author.
  21. //  * This software may not be re-distributed (in part or in whole) in a modified
  22. //    form without clear documentation on how to obtain a copy of the original work.
  23. //  * You may not use this software to directly or indirectly cause harm to others.
  24. //  * This software is provided as-is and without warrantee. Use at your own risk.
  25. //
  26. // For more information, visit HTTP://www.FluidStudios.com
  27. //
  28. // ---------------------------------------------------------------------------------------------------------------------------------
  29. // Originally created on 12/22/2000 by Paul Nettle
  30. //
  31. // Copyright 2000, Fluid Studios, Inc., all rights reserved.
  32. // ---------------------------------------------------------------------------------------------------------------------------------
  33. //
  34. // !!IMPORTANT!!
  35. //
  36. // This software is self-documented with periodic comments. Before you start using this software, perform a search for the string
  37. // "-DOC-" to locate pertinent information about how to use this software.
  38. //
  39. // You are also encouraged to read the comment blocks throughout this source file. They will help you understand how this memory
  40. // tracking software works, so you can better utilize it within your applications.
  41. //
  42. // NOTES:
  43. //
  44. // 1. If you get compiler errors having to do with set_new_handler, then go through this source and search/replace
  45. //    "std::set_new_handler" with "set_new_handler".
  46. //
  47. // 2. This code purposely uses no external routines that allocate RAM (other than the raw allocation routines, such as malloc). We
  48. //    do this because we want this to be as self-contained as possible. As an example, we don't use assert, because when running
  49. //    under WIN32, the assert brings up a dialog box, which allocates RAM. Doing this in the middle of an allocation would be bad.
  50. //
  51. // 3. When trying to override new/delete under MFC (which has its own version of global new/delete) the linker will complain. In
  52. //    order to fix this error, use the compiler option: /FORCE, which will force it to build an executable even with linker errors.
  53. //    Be sure to check those errors each time you compile, otherwise, you may miss a valid linker error.
  54. //
  55. // 4. If you see something that looks odd to you or seems like a strange way of going about doing something, then consider that this
  56. //    code was carefully thought out. If something looks odd, then just assume I've got a good reason for doing it that way (an
  57. //    example is the use of the class MemStaticTimeTracker.)
  58. //
  59. // 5. With MFC applications, you will need to comment out any occurance of "#define new DEBUG_NEW" from all source files.
  60. //
  61. // 6. Include file dependencies are _very_important_ for getting the MMGR to integrate nicely into your application. Be careful if
  62. //    you're including standard includes from within your own project inclues; that will break this very specific dependency order. 
  63. //    It should look like this:
  64. //
  65. //        #include <stdio.h>   // Standard includes MUST come first
  66. //        #include <stdlib.h>  //
  67. //        #include <streamio>  //
  68. //
  69. //        #include "mmgr.h"    // mmgr.h MUST come next
  70. //
  71. //        #include "myfile1.h" // Project includes MUST come last
  72. //        #include "myfile2.h" //
  73. //        #include "myfile3.h" //
  74. //
  75. // ---------------------------------------------------------------------------------------------------------------------------------
  76.  
  77. #include "stdafx.h"
  78.  
  79. #ifdef MMGR
  80.  
  81. #include <iostream>
  82. #include <stdio.h>
  83. #include <stdlib.h>
  84. #include <assert.h>
  85. #include <string.h>
  86. #include <time.h>
  87. #include <stdarg.h>
  88. #include <new>
  89.  
  90. #ifndef    WIN32
  91. #include <unistd.h>
  92. #endif
  93.  
  94. #include "mmgr.h"
  95.  
  96. // ---------------------------------------------------------------------------------------------------------------------------------
  97. // -DOC- If you're like me, it's hard to gain trust in foreign code. This memory manager will try to INDUCE your code to crash (for
  98. // very good reasons... like making bugs obvious as early as possible.) Some people may be inclined to remove this memory tracking
  99. // software if it causes crashes that didn't exist previously. In reality, these new crashes are the BEST reason for using this
  100. // software!
  101. //
  102. // Whether this software causes your application to crash, or if it reports errors, you need to be able to TRUST this software. To
  103. // this end, you are given some very simple debugging tools.
  104. // 
  105. // The quickest way to locate problems is to enable the STRESS_TEST macro (below.) This should catch 95% of the crashes before they
  106. // occur by validating every allocation each time this memory manager performs an allocation function. If that doesn't work, keep
  107. // reading...
  108. //
  109. // If you enable the TEST_MEMORY_MANAGER #define (below), this memory manager will log an entry in the memory.log file each time it
  110. // enters and exits one of its primary allocation handling routines. Each call that succeeds should place an "ENTER" and an "EXIT"
  111. // into the log. If the program crashes within the memory manager, it will log an "ENTER", but not an "EXIT". The log will also
  112. // report the name of the routine.
  113. //
  114. // Just because this memory manager crashes does not mean that there is a bug here! First, an application could inadvertantly damage
  115. // the heap, causing malloc(), realloc() or free() to crash. Also, an application could inadvertantly damage some of the memory used
  116. // by this memory tracking software, causing it to crash in much the same way that a damaged heap would affect the standard
  117. // allocation routines.
  118. //
  119. // In the event of a crash within this code, the first thing you'll want to do is to locate the actual line of code that is
  120. // crashing. You can do this by adding log() entries throughout the routine that crashes, repeating this process until you narrow
  121. // in on the offending line of code. If the crash happens in a standard C allocation routine (i.e. malloc, realloc or free) don't
  122. // bother contacting me, your application has damaged the heap. You can help find the culprit in your code by enabling the
  123. // STRESS_TEST macro (below.)
  124. //
  125. // If you truely suspect a bug in this memory manager (and you had better be sure about it! :) you can contact me at
  126. // midnight@FluidStudios.com. Before you do, however, check for a newer version at:
  127. //
  128. //    http://www.FluidStudios.com/publications.html
  129. //
  130. // When using this debugging aid, make sure that you are NOT setting the alwaysLogAll variable on, otherwise the log could be
  131. // cluttered and hard to read.
  132. // ---------------------------------------------------------------------------------------------------------------------------------
  133.  
  134. //#define    TEST_MEMORY_MANAGER
  135.  
  136. // ---------------------------------------------------------------------------------------------------------------------------------
  137. // -DOC- Enable this sucker if you really want to stress-test your app's memory usage, or to help find hard-to-find bugs
  138. // ---------------------------------------------------------------------------------------------------------------------------------
  139.  
  140. //#define    STRESS_TEST
  141.  
  142. // ---------------------------------------------------------------------------------------------------------------------------------
  143. // -DOC- Enable this sucker if you want to stress-test your app's error-handling. Set RANDOM_FAIL to the percentage of failures you
  144. //       want to test with (0 = none, >100 = all failures).
  145. // ---------------------------------------------------------------------------------------------------------------------------------
  146.  
  147. //#define    RANDOM_FAILURE 10.0
  148.  
  149. // ---------------------------------------------------------------------------------------------------------------------------------
  150. // -DOC- Locals -- modify these flags to suit your needs
  151. // ---------------------------------------------------------------------------------------------------------------------------------
  152.  
  153. #ifdef    STRESS_TEST
  154. static    const    unsigned int    hashBits               = 12;
  155. static        bool        randomWipe             = true;
  156. static        bool        alwaysValidateAll      = true;
  157. static        bool        alwaysLogAll           = true;
  158. static        bool        alwaysWipeAll          = true;
  159. static        bool        cleanupLogOnFirstRun   = true;
  160. static    const    unsigned int    paddingSize            = 1024; // An extra 8K per allocation!
  161. #else
  162. static    const    unsigned int    hashBits               = 12;
  163. static        bool        randomWipe             = false;
  164. static        bool        alwaysValidateAll      = false;
  165. static        bool        alwaysLogAll           = false;
  166. static        bool        alwaysWipeAll          = true;
  167. static        bool        cleanupLogOnFirstRun   = true;
  168. static    const    unsigned int    paddingSize            = 4;
  169. #endif
  170.  
  171. // ---------------------------------------------------------------------------------------------------------------------------------
  172. // We define our own assert, because we don't want to bring up an assertion dialog, since that allocates RAM. Our new assert
  173. // simply declares a forced breakpoint.
  174. //
  175. // The BEOS assert added by Arvid Norberg <arvid@iname.com>.
  176. // ---------------------------------------------------------------------------------------------------------------------------------
  177.  
  178. #ifdef    WIN32
  179.     #ifdef    _DEBUG
  180.     #define    m_assert(x) if ((x) == false) __asm { int 3 }
  181.     #else
  182.     #define    m_assert(x) {}
  183.     #endif
  184. #elif defined(__BEOS__)
  185.     #ifdef DEBUG
  186.         extern void debugger(const char *message);
  187.         #define    m_assert(x) if ((x) == false) debugger("mmgr: assert failed")
  188.     #else
  189.         #define m_assert(x) {}
  190.     #endif
  191. #else    // Linux uses assert, which we can use safely, since it doesn't bring up a dialog within the program.
  192.     #define    m_assert(cond) assert(cond)
  193. #endif
  194.  
  195. // ---------------------------------------------------------------------------------------------------------------------------------
  196. // Here, we turn off our macros because any place in this source file where the word 'new' or the word 'delete' (etc.)
  197. // appear will be expanded by the macro. So to avoid problems using them within this source file, we'll just #undef them.
  198. // ---------------------------------------------------------------------------------------------------------------------------------
  199.  
  200. #undef    new
  201. #undef    delete
  202. #undef    malloc
  203. #undef    calloc
  204. #undef    realloc
  205. #undef    free
  206.  
  207. // ---------------------------------------------------------------------------------------------------------------------------------
  208. // Defaults for the constants & statics in the MemoryManager class
  209. // ---------------------------------------------------------------------------------------------------------------------------------
  210.  
  211. const        unsigned int    m_alloc_unknown        = 0;
  212. const        unsigned int    m_alloc_new            = 1;
  213. const        unsigned int    m_alloc_new_array      = 2;
  214. const        unsigned int    m_alloc_malloc         = 3;
  215. const        unsigned int    m_alloc_calloc         = 4;
  216. const        unsigned int    m_alloc_realloc        = 5;
  217. const        unsigned int    m_alloc_delete         = 6;
  218. const        unsigned int    m_alloc_delete_array   = 7;
  219. const        unsigned int    m_alloc_free           = 8;
  220.  
  221. // ---------------------------------------------------------------------------------------------------------------------------------
  222. // -DOC- Get to know these values. They represent the values that will be used to fill unused and deallocated RAM.
  223. // ---------------------------------------------------------------------------------------------------------------------------------
  224.  
  225. static        unsigned int    prefixPattern          = 0xbaadf00d; // Fill pattern for bytes preceeding allocated blocks
  226. static        unsigned int    postfixPattern         = 0xdeadc0de; // Fill pattern for bytes following allocated blocks
  227. static        unsigned int    unusedPattern          = 0xfeedface; // Fill pattern for freshly allocated blocks
  228. static        unsigned int    releasedPattern        = 0xdeadbeef; // Fill pattern for deallocated blocks
  229.  
  230. // ---------------------------------------------------------------------------------------------------------------------------------
  231. // Other locals
  232. // ---------------------------------------------------------------------------------------------------------------------------------
  233.  
  234. static    const    unsigned int    hashSize               = 1 << hashBits;
  235. static    const    char        *allocationTypes[]     = {"Unknown",
  236.                               "new",     "new[]",  "malloc",   "calloc",
  237.                               "realloc", "delete", "delete[]", "free"};
  238. static        sAllocUnit    *hashTable[hashSize];
  239. static        sAllocUnit    *reservoir;
  240. static        unsigned int    currentAllocationCount = 0;
  241. static        unsigned int    breakOnAllocationCount = 0;
  242. static        sMStats        stats;
  243. static    const    char        *sourceFile            = "??";
  244. static    const    char        *sourceFunc            = "??";
  245. static        unsigned int    sourceLine             = 0;
  246. static        bool        staticDeinitTime       = false;
  247. static        sAllocUnit    **reservoirBuffer      = NULL;
  248. static        unsigned int    reservoirBufferSize    = 0;
  249. static const    char        *memoryLogFile         = "memory.log";
  250. static const    char        *memoryLeakLogFile     = "memleaks.log";
  251. static        void        doCleanupLogOnFirstRun();
  252.  
  253. // ---------------------------------------------------------------------------------------------------------------------------------
  254. // Helper locals and macros to make this fine code thread-safe
  255. // ---------------------------------------------------------------------------------------------------------------------------------
  256.  
  257. static int setOwnerLocked = 0;
  258.  
  259. #ifdef    WIN32
  260.  
  261. static bool criticalSectionInitialized = false;
  262. static CRITICAL_SECTION mmgrCriticalSection;
  263.  
  264. // Lock class. While an instance of this objects exists, the corresponding
  265. // critical section will be locked
  266. class CCriticalSectionLock
  267. {
  268. public:
  269.     CCriticalSectionLock(CRITICAL_SECTION* criticalSection)
  270.     {
  271.         m_criticalSection = criticalSection;
  272.         EnterCriticalSection(m_criticalSection);
  273.     }
  274.  
  275.     ~CCriticalSectionLock()
  276.     {
  277.         LeaveCriticalSection(m_criticalSection);
  278.     }
  279. private:
  280.     CRITICAL_SECTION* m_criticalSection;
  281. };
  282.  
  283. // This macro will be added to all functions which can be called from outside this file.
  284. #define LOCK if (!criticalSectionInitialized) { \
  285.                 InitializeCriticalSection(&mmgrCriticalSection); \
  286.                 criticalSectionInitialized = true; } \
  287.                 CCriticalSectionLock lock(&mmgrCriticalSection);
  288.  
  289. #define LOCKPERSISTENT if (!criticalSectionInitialized) { \
  290.                 InitializeCriticalSection(&mmgrCriticalSection); \
  291.                 criticalSectionInitialized = true; } \
  292.                 EnterCriticalSection(&mmgrCriticalSection);
  293. #define UNLOCK     LeaveCriticalSection(&mmgrCriticalSection);
  294. #else
  295. // This macro will be added to all functions which can be called from outside this file.
  296. #define LOCK
  297. #define LOCKPERSISTENT
  298. #define UNLOCK
  299. #endif
  300.  
  301. // ---------------------------------------------------------------------------------------------------------------------------------
  302. // Local functions only
  303. // ---------------------------------------------------------------------------------------------------------------------------------
  304.  
  305. static    void    log(const char *format, ...)
  306. {
  307.     // Cleanup the log?
  308.  
  309.     if (cleanupLogOnFirstRun) doCleanupLogOnFirstRun();
  310.  
  311.     // Build the buffer
  312.  
  313.     static char buffer[2048];
  314.     va_list    ap;
  315.     va_start(ap, format);
  316.     vsprintf(buffer, format, ap);
  317.     va_end(ap);
  318.  
  319.     // Open the log file
  320.  
  321.     FILE    *fp = fopen(memoryLogFile, "ab");
  322.  
  323.     // If you hit this assert, then the memory logger is unable to log information to a file (can't open the file for some
  324.     // reason.) You can interrogate the variable 'buffer' to see what was supposed to be logged (but won't be.)
  325.     m_assert(fp);
  326.  
  327.     if (!fp) return;
  328.  
  329.     // Spit out the data to the log
  330.  
  331.     fprintf(fp, "%s\r\n", buffer);
  332.     fclose(fp);
  333. }
  334.  
  335. // ---------------------------------------------------------------------------------------------------------------------------------
  336.  
  337. static    void    doCleanupLogOnFirstRun()
  338. {
  339.     if (cleanupLogOnFirstRun)
  340.     {
  341.         unlink(memoryLogFile);
  342.         cleanupLogOnFirstRun = false;
  343.  
  344.         // Print a header for the log
  345.  
  346.         time_t    t = time(NULL);
  347.         log("--------------------------------------------------------------------------------");
  348.         log("");
  349.         log("      %s - Memory logging file created on %s", memoryLogFile, asctime(localtime(&t)));
  350.         log("--------------------------------------------------------------------------------");
  351.         log("");
  352.         log("This file contains a log of all memory operations performed during the last run.");
  353.         log("");
  354.         log("Interrogate this file to track errors or to help track down memory-related");
  355.         log("issues. You can do this by tracing the allocations performed by a specific owner");
  356.         log("or by tracking a specific address through a series of allocations and");
  357.         log("reallocations.");
  358.         log("");
  359.         log("There is a lot of useful information here which, when used creatively, can be");
  360.         log("extremely helpful.");
  361.         log("");
  362.         log("Note that the following guides are used throughout this file:");
  363.         log("");
  364.         log("   [!] - Error");
  365.         log("   [+] - Allocation");
  366.         log("   [~] - Reallocation");
  367.         log("   [-] - Deallocation");
  368.         log("   [I] - Generic information");
  369.         log("   [F] - Failure induced for the purpose of stress-testing your application");
  370.         log("   [D] - Information used for debugging this memory manager");
  371.         log("");
  372.         log("...so, to find all errors in the file, search for \"[!]\"");
  373.         log("");
  374.         log("--------------------------------------------------------------------------------");
  375.     }
  376. }
  377.  
  378. // ---------------------------------------------------------------------------------------------------------------------------------
  379.  
  380. static    const char    *sourceFileStripper(const char *sourceFile)
  381. {
  382.     char    *ptr = strrchr(sourceFile, '\\');
  383.     if (ptr) return ptr + 1;
  384.     ptr = strrchr(sourceFile, '/');
  385.     if (ptr) return ptr + 1;
  386.     return sourceFile;
  387. }
  388.  
  389. // ---------------------------------------------------------------------------------------------------------------------------------
  390.  
  391. static    const char    *ownerString(const char *sourceFile, const unsigned int sourceLine, const char *sourceFunc)
  392. {
  393.     static    char    str[90];
  394.     memset(str, 0, sizeof(str));
  395.     sprintf(str, "%s(%05d)::%s", sourceFileStripper(sourceFile), sourceLine, sourceFunc);
  396.     return str;
  397. }
  398.  
  399. // ---------------------------------------------------------------------------------------------------------------------------------
  400.  
  401. static    const char    *insertCommas(unsigned int value)
  402. {
  403.     static    char    str[30];
  404.     memset(str, 0, sizeof(str));
  405.  
  406.     sprintf(str, "%u", value);
  407.     if (strlen(str) > 3)
  408.     {
  409.         memmove(&str[strlen(str)-3], &str[strlen(str)-4], 4);
  410.         str[strlen(str) - 4] = ',';
  411.     }
  412.     if (strlen(str) > 7)
  413.     {
  414.         memmove(&str[strlen(str)-7], &str[strlen(str)-8], 8);
  415.         str[strlen(str) - 8] = ',';
  416.     }
  417.     if (strlen(str) > 11)
  418.     {
  419.         memmove(&str[strlen(str)-11], &str[strlen(str)-12], 12);
  420.         str[strlen(str) - 12] = ',';
  421.     }
  422.  
  423.     return str;
  424. }
  425.  
  426. // ---------------------------------------------------------------------------------------------------------------------------------
  427.  
  428. static    const char    *memorySizeString(unsigned long size)
  429. {
  430.     static    char    str[90];
  431.          if (size > (1024*1024))    sprintf(str, "%10s (%7.2fM)", insertCommas(size), static_cast<float>(size) / (1024.0f * 1024.0f));
  432.     else if (size > 1024)        sprintf(str, "%10s (%7.2fK)", insertCommas(size), static_cast<float>(size) / 1024.0f);
  433.     else                sprintf(str, "%10s bytes     ", insertCommas(size));
  434.     return str;
  435. }
  436.  
  437. // ---------------------------------------------------------------------------------------------------------------------------------
  438.  
  439. static    sAllocUnit    *findAllocUnit(const void *reportedAddress)
  440. {
  441.     // Just in case...
  442.     m_assert(reportedAddress != NULL);
  443.  
  444.     // Use the address to locate the hash index. Note that we shift off the lower four bits. This is because most allocated
  445.     // addresses will be on four-, eight- or even sixteen-byte boundaries. If we didn't do this, the hash index would not have
  446.     // very good coverage.
  447.  
  448.     unsigned int    hashIndex = (reinterpret_cast<unsigned int>(const_cast<void *>(reportedAddress)) >> 4) & (hashSize - 1);
  449.     sAllocUnit    *ptr = hashTable[hashIndex];
  450.     while(ptr)
  451.     {
  452.         if (ptr->reportedAddress == reportedAddress) return ptr;
  453.         ptr = ptr->next;
  454.     }
  455.  
  456.     return NULL;
  457. }
  458.  
  459. // ---------------------------------------------------------------------------------------------------------------------------------
  460.  
  461. static    size_t    calculateActualSize(const size_t reportedSize)
  462. {
  463.     // We use DWORDS as our padding, and a long is guaranteed to be 4 bytes, but an int is not (ANSI defines an int as
  464.     // being the standard word size for a processor; on a 32-bit machine, that's 4 bytes, but on a 64-bit machine, it's
  465.     // 8 bytes, which means an int can actually be larger than a long.)
  466.  
  467.     return reportedSize + paddingSize * sizeof(long) * 2;
  468. }
  469.  
  470. // ---------------------------------------------------------------------------------------------------------------------------------
  471.  
  472. static    size_t    calculateReportedSize(const size_t actualSize)
  473. {
  474.     // We use DWORDS as our padding, and a long is guaranteed to be 4 bytes, but an int is not (ANSI defines an int as
  475.     // being the standard word size for a processor; on a 32-bit machine, that's 4 bytes, but on a 64-bit machine, it's
  476.     // 8 bytes, which means an int can actually be larger than a long.)
  477.  
  478.     return actualSize - paddingSize * sizeof(long) * 2;
  479. }
  480.  
  481. // ---------------------------------------------------------------------------------------------------------------------------------
  482.  
  483. static    void    *calculateReportedAddress(const void *actualAddress)
  484. {
  485.     // We allow this...
  486.  
  487.     if (!actualAddress) return NULL;
  488.  
  489.     // JUst account for the padding
  490.  
  491.     return reinterpret_cast<void *>(const_cast<char *>(reinterpret_cast<const char *>(actualAddress) + sizeof(long) * paddingSize));
  492. }
  493.  
  494. // ---------------------------------------------------------------------------------------------------------------------------------
  495.  
  496. static    void    wipeWithPattern(sAllocUnit *allocUnit, unsigned long pattern, const unsigned int originalReportedSize = 0)
  497. {
  498.     // For a serious test run, we use wipes of random a random value. However, if this causes a crash, we don't want it to
  499.     // crash in a differnt place each time, so we specifically DO NOT call srand. If, by chance your program calls srand(),
  500.     // you may wish to disable that when running with a random wipe test. This will make any crashes more consistent so they
  501.     // can be tracked down easier.
  502.  
  503.     if (randomWipe)
  504.     {
  505.         pattern = ((rand() & 0xff) << 24) | ((rand() & 0xff) << 16) | ((rand() & 0xff) << 8) | (rand() & 0xff);
  506.     }
  507.  
  508.     // -DOC- We should wipe with 0's if we're not in debug mode, so we can help hide bugs if possible when we release the
  509.     // product. So uncomment the following line for releases.
  510.     //
  511.     // Note that the "alwaysWipeAll" should be turned on for this to have effect, otherwise it won't do much good. But we'll
  512.     // leave it this way (as an option) because this does slow things down.
  513. //    pattern = 0;
  514.  
  515.     // This part of the operation is optional
  516.  
  517.     if (alwaysWipeAll && allocUnit->reportedSize > originalReportedSize)
  518.     {
  519.         // Fill the bulk
  520.  
  521.         long    *lptr = reinterpret_cast<long *>(reinterpret_cast<char *>(allocUnit->reportedAddress) + originalReportedSize);
  522.         int    length = static_cast<int>(allocUnit->reportedSize - originalReportedSize);
  523.         int    i;
  524.         for (i = 0; i < (length >> 2); i++, lptr++)
  525.         {
  526.             *lptr = pattern;
  527.         }
  528.  
  529.         // Fill the remainder
  530.  
  531.         unsigned int    shiftCount = 0;
  532.         char        *cptr = reinterpret_cast<char *>(lptr);
  533.         for (i = 0; i < (length & 0x3); i++, cptr++, shiftCount += 8)
  534.         {
  535.             *cptr = static_cast<char>((pattern & (0xff << shiftCount)) >> shiftCount);
  536.         }
  537.     }
  538.  
  539.     // Write in the prefix/postfix bytes
  540.  
  541.     long        *pre = reinterpret_cast<long *>(allocUnit->actualAddress);
  542.     long        *post = reinterpret_cast<long *>(reinterpret_cast<char *>(allocUnit->actualAddress) + allocUnit->actualSize - paddingSize * sizeof(long));
  543.     for (unsigned int i = 0; i < paddingSize; i++, pre++, post++)
  544.     {
  545.         *pre = prefixPattern;
  546.         *post = postfixPattern;
  547.     }
  548. }
  549.  
  550. // ---------------------------------------------------------------------------------------------------------------------------------
  551.  
  552. static    void    dumpAllocations(FILE *fp)
  553. {
  554.     fprintf(fp, "Alloc.   Addr       Size       Addr       Size                        BreakOn BreakOn              \r\n");
  555.     fprintf(fp, "Number Reported   Reported    Actual     Actual     Unused    Method  Dealloc Realloc Allocated by \r\n");
  556.     fprintf(fp, "------ ---------- ---------- ---------- ---------- ---------- -------- ------- ------- --------------------------------------------------- \r\n");
  557.  
  558.  
  559.     for (unsigned int i = 0; i < hashSize; i++)
  560.     {
  561.         sAllocUnit *ptr = hashTable[i];
  562.         while(ptr)
  563.         {
  564.             fprintf(fp, "%06d 0x%08X 0x%08X 0x%08X 0x%08X 0x%08X %-8s    %c       %c    %s\r\n",
  565.                 ptr->allocationNumber,
  566.                 reinterpret_cast<unsigned int>(ptr->reportedAddress), ptr->reportedSize,
  567.                 reinterpret_cast<unsigned int>(ptr->actualAddress), ptr->actualSize,
  568.                 m_calcUnused(ptr),
  569.                 allocationTypes[ptr->allocationType],
  570.                 ptr->breakOnDealloc ? 'Y':'N',
  571.                 ptr->breakOnRealloc ? 'Y':'N',
  572.                 ownerString(ptr->sourceFile, ptr->sourceLine, ptr->sourceFunc));
  573.             ptr = ptr->next;
  574.         }
  575.     }
  576. }
  577.  
  578. // ---------------------------------------------------------------------------------------------------------------------------------
  579.  
  580. static    void    dumpLeakReport()
  581. {
  582.     // Open the report file
  583.  
  584.     FILE    *fp = fopen(memoryLeakLogFile, "w+b");
  585.  
  586.     // If you hit this assert, then the memory report generator is unable to log information to a file (can't open the file for
  587.     // some reason.)
  588.     m_assert(fp);
  589.     if (!fp) return;
  590.  
  591.     // Any leaks?
  592.  
  593.     // Header
  594.  
  595.     static  char    timeString[25];
  596.     memset(timeString, 0, sizeof(timeString));
  597.     time_t  t = time(NULL);
  598.     struct  tm *tme = localtime(&t);
  599.     fprintf(fp, " ---------------------------------------------------------------------------------------------------------------------------------- \r\n");
  600.     fprintf(fp, "|                                          Memory leak report for:  %02d/%02d/%04d %02d:%02d:%02d                                            |\r\n", tme->tm_mon + 1, tme->tm_mday, tme->tm_year + 1900, tme->tm_hour, tme->tm_min, tme->tm_sec);
  601.     fprintf(fp, " ---------------------------------------------------------------------------------------------------------------------------------- \r\n");
  602.     fprintf(fp, "\r\n");
  603.     fprintf(fp, "\r\n");
  604.     if (stats.totalAllocUnitCount)
  605.     {
  606.         fprintf(fp, "%d memory leak%s found:\r\n", stats.totalAllocUnitCount, stats.totalAllocUnitCount == 1 ? "":"s");
  607.     }
  608.     else
  609.     {
  610.         fprintf(fp, "Congratulations! No memory leaks found!\r\n");
  611.  
  612.         // We can finally free up our own memory allocations
  613.  
  614.         if (reservoirBuffer)
  615.         {
  616.             for (unsigned int i = 0; i < reservoirBufferSize; i++)
  617.             {
  618.                 free(reservoirBuffer[i]);
  619.             }
  620.             free(reservoirBuffer);
  621.             reservoirBuffer = 0;
  622.             reservoirBufferSize = 0;
  623.             reservoir = NULL;
  624.         }
  625.     }
  626.     fprintf(fp, "\r\n");
  627.  
  628.     if (stats.totalAllocUnitCount)
  629.     {
  630.         dumpAllocations(fp);
  631.     }
  632.  
  633.     fclose(fp);
  634. }
  635.  
  636. // ---------------------------------------------------------------------------------------------------------------------------------
  637. // We use a static class to let us know when we're in the midst of static deinitialization
  638. // ---------------------------------------------------------------------------------------------------------------------------------
  639.  
  640. class    MemStaticTimeTracker
  641. {
  642. public:
  643.     MemStaticTimeTracker() {doCleanupLogOnFirstRun();}
  644.     ~MemStaticTimeTracker() {staticDeinitTime = true; dumpLeakReport();}
  645. };
  646. static    MemStaticTimeTracker    mstt;
  647.  
  648. // ---------------------------------------------------------------------------------------------------------------------------------
  649. // -DOC- Flags & options -- Call these routines to enable/disable the following options
  650. // ---------------------------------------------------------------------------------------------------------------------------------
  651.  
  652. bool    &m_alwaysValidateAll()
  653. {
  654.     // Force a validation of all allocation units each time we enter this software
  655.     return alwaysValidateAll;
  656. }
  657.  
  658. // ---------------------------------------------------------------------------------------------------------------------------------
  659.  
  660. bool    &m_alwaysLogAll()
  661. {
  662.     // Force a log of every allocation & deallocation into memory.log
  663.     return alwaysLogAll;
  664. }
  665.  
  666. // ---------------------------------------------------------------------------------------------------------------------------------
  667.  
  668. bool    &m_alwaysWipeAll()
  669. {
  670.     // Force this software to always wipe memory with a pattern when it is being allocated/dallocated
  671.     return alwaysWipeAll;
  672. }
  673.  
  674. // ---------------------------------------------------------------------------------------------------------------------------------
  675.  
  676. bool    &m_randomeWipe()
  677. {
  678.     // Force this software to use a random pattern when wiping memory -- good for stress testing
  679.     return randomWipe;
  680. }
  681.  
  682. // ---------------------------------------------------------------------------------------------------------------------------------
  683. // -DOC- Simply call this routine with the address of an allocated block of RAM, to cause it to force a breakpoint when it is
  684. // reallocated.
  685. // ---------------------------------------------------------------------------------------------------------------------------------
  686.  
  687. bool    &m_breakOnRealloc(void *reportedAddress)
  688. {
  689.     LOCK;
  690.  
  691.     // Locate the existing allocation unit
  692.  
  693.     sAllocUnit    *au = findAllocUnit(reportedAddress);
  694.  
  695.     // If you hit this assert, you tried to set a breakpoint on reallocation for an address that doesn't exist. Interrogate the
  696.     // stack frame or the variable 'au' to see which allocation this is.
  697.     m_assert(au != NULL);
  698.  
  699.     // If you hit this assert, you tried to set a breakpoint on reallocation for an address that wasn't allocated in a way that
  700.     // is compatible with reallocation.
  701.     m_assert(au->allocationType == m_alloc_malloc ||
  702.          au->allocationType == m_alloc_calloc ||
  703.          au->allocationType == m_alloc_realloc);
  704.  
  705.     return au->breakOnRealloc;
  706. }
  707.  
  708. // ---------------------------------------------------------------------------------------------------------------------------------
  709. // -DOC- Simply call this routine with the address of an allocated block of RAM, to cause it to force a breakpoint when it is
  710. // deallocated.
  711. // ---------------------------------------------------------------------------------------------------------------------------------
  712.  
  713. bool    &m_breakOnDealloc(void *reportedAddress)
  714. {
  715.     LOCK;
  716.  
  717.     // Locate the existing allocation unit
  718.  
  719.     sAllocUnit    *au = findAllocUnit(reportedAddress);
  720.  
  721.     // If you hit this assert, you tried to set a breakpoint on deallocation for an address that doesn't exist. Interrogate the
  722.     // stack frame or the variable 'au' to see which allocation this is.
  723.     m_assert(au != NULL);
  724.  
  725.     return au->breakOnDealloc;
  726. }
  727.  
  728. // ---------------------------------------------------------------------------------------------------------------------------------
  729. // -DOC- When tracking down a difficult bug, use this routine to force a breakpoint on a specific allocation count
  730. // ---------------------------------------------------------------------------------------------------------------------------------
  731.  
  732. void    m_breakOnAllocation(unsigned int count)
  733. {
  734.     breakOnAllocationCount = count;
  735. }
  736.  
  737. // ---------------------------------------------------------------------------------------------------------------------------------
  738. // Used by the macros
  739. // ---------------------------------------------------------------------------------------------------------------------------------
  740.  
  741. void    m_setOwner(const char *file, const unsigned int line, const char *func)
  742. {
  743.     // You're probably wondering about this...
  744.     //
  745.     // It's important for this memory manager to primarily work with global new/delete in their original forms (i.e. with
  746.     // no extra parameters.) In order to do this, we use macros that call this function prior to operators new & delete. This
  747.     // is fine... usually. Here's what actually happens when you use this macro to delete an object:
  748.     //
  749.     // m_setOwner(__FILE__, __LINE__, __FUNCTION__) --> object::~object() --> delete
  750.     //
  751.     // Note that the compiler inserts a call to the object's destructor just prior to calling our overridden operator delete.
  752.     // But what happens when we delete an object whose destructor deletes another object, whose desctuctor deletes another
  753.     // object? Here's a diagram (indentation follows stack depth):
  754.     //
  755.     // m_setOwner(...) -> ~obj1()                          // original call to delete obj1
  756.     //     m_setOwner(...) -> ~obj2()                      // obj1's destructor deletes obj2
  757.     //         m_setOwner(...) -> ~obj3()                  // obj2's destructor deletes obj3
  758.     //             ...                                     // obj3's destructor just does some stuff
  759.     //         delete                                      // back in obj2's destructor, we call delete
  760.     //     delete                                          // back in obj1's destructor, we call delete
  761.     // delete                                              // back to our original call, we call delete
  762.     //
  763.     // Because m_setOwner() just sets up some static variables (below) it's important that each call to m_setOwner() and
  764.     // successive calls to new/delete alternate. However, in this case, three calls to m_setOwner() happen in succession
  765.     // followed by three calls to delete in succession (with a few calls to destructors mixed in for fun.) This means that
  766.     // only the final call to delete (in this chain of events) will have the proper reporting, and the first two in the chain
  767.     // will not have ANY owner-reporting information. The deletes will still work fine, we just won't know who called us.
  768.     //
  769.     // "Then build a stack, my friend!" you might think... but it's a very common thing that people will be working with third-
  770.     // party libraries (including MFC under Windows) which is not compiled with this memory manager's macros. In those cases,
  771.     // m_setOwner() is never called, and rightfully should not have the proper trace-back information. So if one of the
  772.     // destructors in the chain ends up being a call to a delete from a non-mmgr-compiled library, the stack will get confused.
  773.     //
  774.     // I've been unable to find a solution to this problem, but at least we can detect it and report the data before we
  775.     // lose it. That's what this is all about. It makes it somewhat confusing to read in the logs, but at least ALL the
  776.     // information is present...
  777.     //
  778.     // There's a caveat here... The compiler is not required to call operator delete if the value being deleted is NULL.
  779.     // In this case, any call to delete with a NULL will sill call m_setOwner(), which will make m_setOwner() think that
  780.     // there is a destructor chain becuase we setup the variables, but nothing gets called to clear them. Because of this
  781.     // we report a "Possible destructor chain".
  782.     //
  783.     // Thanks to J. Woznack (from Kodiak Interactive Software Studios -- www.kodiakgames.com) for pointing this out.
  784.  
  785.     LOCKPERSISTENT;
  786.     setOwnerLocked++;
  787.  
  788.     if (sourceLine && alwaysLogAll)
  789.     {
  790.         log("[I] NOTE! Possible destructor chain: previous owner is %s", ownerString(sourceFile, sourceLine, sourceFunc));
  791.     }
  792.  
  793.     // Okay... save this stuff off so we can keep track of the caller
  794.  
  795.     sourceFile = file;
  796.     sourceLine = line;
  797.     sourceFunc = func;
  798.  
  799.     if (!sourceLine)
  800.     {
  801.         setOwnerLocked--;
  802.         UNLOCK;
  803.         UNLOCK;
  804.     }
  805. }
  806.  
  807. // ---------------------------------------------------------------------------------------------------------------------------------
  808.  
  809. static    void    resetGlobals()
  810. {
  811.     sourceFile = "??";
  812.     sourceLine = 0;
  813.     sourceFunc = "??";
  814. }
  815.  
  816. // ---------------------------------------------------------------------------------------------------------------------------------
  817. // Global new/new[]
  818. //
  819. // These are the standard new/new[] operators. They are merely interface functions that operate like normal new/new[], but use our
  820. // memory tracking routines.
  821. // ---------------------------------------------------------------------------------------------------------------------------------
  822.  
  823. void    *operator new(size_t reportedSize)
  824. {
  825.     LOCK
  826.  
  827.     if (setOwnerLocked)
  828.     {
  829.         UNLOCK;
  830.         setOwnerLocked--;
  831.     }
  832.  
  833.     #ifdef TEST_MEMORY_MANAGER
  834.     log("[D] ENTER: new");
  835.     #endif
  836.  
  837.     // Save these off...
  838.  
  839.     const    char        *file = sourceFile;
  840.     const    unsigned int    line = sourceLine;
  841.     const    char        *func = sourceFunc;
  842.  
  843.     // ANSI says: allocation requests of 0 bytes will still return a valid value
  844.  
  845.     if (reportedSize == 0) reportedSize = 1;
  846.  
  847.     // ANSI says: loop continuously because the error handler could possibly free up some memory
  848.  
  849.     for(;;)
  850.     {
  851.         // Try the allocation
  852.  
  853.         void    *ptr = m_allocator(file, line, func, m_alloc_new, reportedSize);
  854.         if (ptr)
  855.         {
  856.             #ifdef TEST_MEMORY_MANAGER
  857.             log("[D] EXIT : new");
  858.             #endif
  859.             return ptr;
  860.         }
  861.  
  862.         // There isn't a way to determine the new handler, except through setting it. So we'll just set it to NULL, then
  863.         // set it back again.
  864.  
  865.         new_handler    nh = std::set_new_handler(0);
  866.         std::set_new_handler(nh);
  867.  
  868.         // If there is an error handler, call it
  869.  
  870.         if (nh)
  871.         {
  872.             (*nh)();
  873.         }
  874.  
  875.         // Otherwise, throw the exception
  876.  
  877.         else
  878.         {
  879.             #ifdef TEST_MEMORY_MANAGER
  880.             log("[D] EXIT : new");
  881.             #endif
  882.             throw std::bad_alloc();
  883.         }
  884.     }
  885. }
  886.  
  887. // ---------------------------------------------------------------------------------------------------------------------------------
  888.  
  889. void    *operator new[](size_t reportedSize)
  890. {
  891.     LOCK
  892.  
  893.     if (setOwnerLocked)
  894.     {
  895.         UNLOCK;
  896.         setOwnerLocked--;
  897.     }
  898.  
  899.     #ifdef TEST_MEMORY_MANAGER
  900.     log("[D] ENTER: new[]");
  901.     #endif
  902.  
  903.     // Save these off...
  904.  
  905.     const    char        *file = sourceFile;
  906.     const    unsigned int    line = sourceLine;
  907.     const    char        *func = sourceFunc;
  908.  
  909.     // The ANSI standard says that allocation requests of 0 bytes will still return a valid value
  910.  
  911.     if (reportedSize == 0) reportedSize = 1;
  912.  
  913.     // ANSI says: loop continuously because the error handler could possibly free up some memory
  914.  
  915.     for(;;)
  916.     {
  917.         // Try the allocation
  918.  
  919.         void    *ptr = m_allocator(file, line, func, m_alloc_new_array, reportedSize);
  920.         if (ptr)
  921.         {
  922.             #ifdef TEST_MEMORY_MANAGER
  923.             log("[D] EXIT : new[]");
  924.             #endif
  925.             return ptr;
  926.         }
  927.  
  928.         // There isn't a way to determine the new handler, except through setting it. So we'll just set it to NULL, then
  929.         // set it back again.
  930.  
  931.         new_handler    nh = std::set_new_handler(0);
  932.         std::set_new_handler(nh);
  933.  
  934.         // If there is an error handler, call it
  935.  
  936.         if (nh)
  937.         {
  938.             (*nh)();
  939.         }
  940.  
  941.         // Otherwise, throw the exception
  942.  
  943.         else
  944.         {
  945.             #ifdef TEST_MEMORY_MANAGER
  946.             log("[D] EXIT : new[]");
  947.             #endif
  948.             throw std::bad_alloc();
  949.         }
  950.     }
  951. }
  952.  
  953. // ---------------------------------------------------------------------------------------------------------------------------------
  954. // Other global new/new[]
  955. //
  956. // These are the standard new/new[] operators as used by Microsoft's memory tracker. We don't want them interfering with our memory
  957. // tracking efforts. Like the previous versions, these are merely interface functions that operate like normal new/new[], but use
  958. // our memory tracking routines.
  959. // ---------------------------------------------------------------------------------------------------------------------------------
  960.  
  961. void    *operator new(size_t reportedSize, const char *sourceFile, int sourceLine)
  962. {
  963.     LOCK
  964.  
  965.     if (setOwnerLocked)
  966.     {
  967.         UNLOCK;
  968.         setOwnerLocked--;
  969.     }
  970.  
  971.     #ifdef TEST_MEMORY_MANAGER
  972.     log("[D] ENTER: new");
  973.     #endif
  974.  
  975.     // The ANSI standard says that allocation requests of 0 bytes will still return a valid value
  976.  
  977.     if (reportedSize == 0) reportedSize = 1;
  978.  
  979.     // ANSI says: loop continuously because the error handler could possibly free up some memory
  980.  
  981.     for(;;)
  982.     {
  983.         // Try the allocation
  984.  
  985.         void    *ptr = m_allocator(sourceFile, sourceLine, "??", m_alloc_new, reportedSize);
  986.         if (ptr)
  987.         {
  988.             #ifdef TEST_MEMORY_MANAGER
  989.             log("[D] EXIT : new");
  990.             #endif
  991.             return ptr;
  992.         }
  993.  
  994.         // There isn't a way to determine the new handler, except through setting it. So we'll just set it to NULL, then
  995.         // set it back again.
  996.  
  997.         new_handler    nh = std::set_new_handler(0);
  998.         std::set_new_handler(nh);
  999.  
  1000.         // If there is an error handler, call it
  1001.  
  1002.         if (nh)
  1003.         {
  1004.             (*nh)();
  1005.         }
  1006.  
  1007.         // Otherwise, throw the exception
  1008.  
  1009.         else
  1010.         {
  1011.             #ifdef TEST_MEMORY_MANAGER
  1012.             log("[D] EXIT : new");
  1013.             #endif
  1014.             throw std::bad_alloc();
  1015.         }
  1016.     }
  1017. }
  1018.  
  1019. // ---------------------------------------------------------------------------------------------------------------------------------
  1020.  
  1021. void    *operator new[](size_t reportedSize, const char *sourceFile, int sourceLine)
  1022. {
  1023.     LOCK
  1024.  
  1025.     if (setOwnerLocked)
  1026.     {
  1027.         UNLOCK;
  1028.         setOwnerLocked--;
  1029.     }
  1030.  
  1031.     #ifdef TEST_MEMORY_MANAGER
  1032.     log("[D] ENTER: new[]");
  1033.     #endif
  1034.  
  1035.     // The ANSI standard says that allocation requests of 0 bytes will still return a valid value
  1036.  
  1037.     if (reportedSize == 0) reportedSize = 1;
  1038.  
  1039.     // ANSI says: loop continuously because the error handler could possibly free up some memory
  1040.  
  1041.     for(;;)
  1042.     {
  1043.         // Try the allocation
  1044.  
  1045.         void    *ptr = m_allocator(sourceFile, sourceLine, "??", m_alloc_new_array, reportedSize);
  1046.         if (ptr)
  1047.         {
  1048.             #ifdef TEST_MEMORY_MANAGER
  1049.             log("[D] EXIT : new[]");
  1050.             #endif
  1051.             return ptr;
  1052.         }
  1053.  
  1054.         // There isn't a way to determine the new handler, except through setting it. So we'll just set it to NULL, then
  1055.         // set it back again.
  1056.  
  1057.         new_handler    nh = std::set_new_handler(0);
  1058.         std::set_new_handler(nh);
  1059.  
  1060.         // If there is an error handler, call it
  1061.  
  1062.         if (nh)
  1063.         {
  1064.             (*nh)();
  1065.         }
  1066.  
  1067.         // Otherwise, throw the exception
  1068.  
  1069.         else
  1070.         {
  1071.             #ifdef TEST_MEMORY_MANAGER
  1072.             log("[D] EXIT : new[]");
  1073.             #endif
  1074.             throw std::bad_alloc();
  1075.         }
  1076.     }
  1077. }
  1078.  
  1079. // ---------------------------------------------------------------------------------------------------------------------------------
  1080. // Global delete/delete[]
  1081. //
  1082. // These are the standard delete/delete[] operators. They are merely interface functions that operate like normal delete/delete[],
  1083. // but use our memory tracking routines.
  1084. // ---------------------------------------------------------------------------------------------------------------------------------
  1085.  
  1086. void    operator delete(void *reportedAddress)
  1087. {
  1088.     LOCK
  1089.  
  1090.     if (setOwnerLocked)
  1091.     {
  1092.         UNLOCK;
  1093.         setOwnerLocked--;
  1094.     }
  1095.  
  1096.     #ifdef TEST_MEMORY_MANAGER
  1097.     log("[D] ENTER: delete");
  1098.     #endif
  1099.  
  1100.     // ANSI says: delete & delete[] allow NULL pointers (they do nothing)
  1101.  
  1102.     if (reportedAddress) m_deallocator(sourceFile, sourceLine, sourceFunc, m_alloc_delete, reportedAddress);
  1103.     else if (alwaysLogAll) log("[-] ----- %8s of NULL                      by %s", allocationTypes[m_alloc_delete], ownerString(sourceFile, sourceLine, sourceFunc));
  1104.  
  1105.     // Resetting the globals insures that if at some later time, somebody calls our memory manager from an unknown
  1106.     // source (i.e. they didn't include our H file) then we won't think it was the last allocation.
  1107.  
  1108.     resetGlobals();
  1109.  
  1110.     #ifdef TEST_MEMORY_MANAGER
  1111.     log("[D] EXIT : delete");
  1112.     #endif
  1113. }
  1114.  
  1115. // ---------------------------------------------------------------------------------------------------------------------------------
  1116.  
  1117. void    operator delete[](void *reportedAddress)
  1118. {
  1119.     LOCK
  1120.  
  1121.     if (setOwnerLocked)
  1122.     {
  1123.         UNLOCK;
  1124.         setOwnerLocked--;
  1125.     }
  1126.  
  1127.     #ifdef TEST_MEMORY_MANAGER
  1128.     log("[D] ENTER: delete[]");
  1129.     #endif
  1130.  
  1131.     // ANSI says: delete & delete[] allow NULL pointers (they do nothing)
  1132.  
  1133.     if (reportedAddress) m_deallocator(sourceFile, sourceLine, sourceFunc, m_alloc_delete_array, reportedAddress);
  1134.     else if (alwaysLogAll)
  1135.         log("[-] ----- %8s of NULL                      by %s", allocationTypes[m_alloc_delete_array], ownerString(sourceFile, sourceLine, sourceFunc));
  1136.  
  1137.     // Resetting the globals insures that if at some later time, somebody calls our memory manager from an unknown
  1138.     // source (i.e. they didn't include our H file) then we won't think it was the last allocation.
  1139.  
  1140.     resetGlobals();
  1141.  
  1142.     #ifdef TEST_MEMORY_MANAGER
  1143.     log("[D] EXIT : delete[]");
  1144.     #endif
  1145. }
  1146.  
  1147. // ---------------------------------------------------------------------------------------------------------------------------------
  1148. // Allocate memory and track it
  1149. // ---------------------------------------------------------------------------------------------------------------------------------
  1150.  
  1151. void    *m_allocator(const char *sourceFile, const unsigned int sourceLine, const char *sourceFunc, const unsigned int allocationType, const size_t reportedSize)
  1152. {
  1153.     LOCK
  1154.  
  1155.     try
  1156.     {
  1157.         #ifdef TEST_MEMORY_MANAGER
  1158.         log("[D] ENTER: m_allocator()");
  1159.         #endif
  1160.  
  1161.         // Increase our allocation count
  1162.  
  1163.         currentAllocationCount++;
  1164.  
  1165.         // Log the request
  1166.  
  1167.         if (alwaysLogAll) log("[+] %05d %8s of size 0x%08X(%08d) by %s", currentAllocationCount, allocationTypes[allocationType], reportedSize, reportedSize, ownerString(sourceFile, sourceLine, sourceFunc));
  1168.  
  1169.         // If you hit this assert, you requested a breakpoint on a specific allocation count
  1170.         m_assert(currentAllocationCount != breakOnAllocationCount);
  1171.  
  1172.         // If necessary, grow the reservoir of unused allocation units
  1173.  
  1174.         if (!reservoir)
  1175.         {
  1176.             // Allocate 256 reservoir elements
  1177.  
  1178.             reservoir = (sAllocUnit *) malloc(sizeof(sAllocUnit) * 256);
  1179.  
  1180.             // If you hit this assert, then the memory manager failed to allocate internal memory for tracking the
  1181.             // allocations
  1182.             m_assert(reservoir != NULL);
  1183.  
  1184.             // Danger Will Robinson!
  1185.  
  1186.             if (reservoir == NULL) throw "Unable to allocate RAM for internal memory tracking data";
  1187.  
  1188.             // Build a linked-list of the elements in our reservoir
  1189.  
  1190.             memset(reservoir, 0, sizeof(sAllocUnit) * 256);
  1191.             for (unsigned int i = 0; i < 256 - 1; i++)
  1192.             {
  1193.                 reservoir[i].next = &reservoir[i+1];
  1194.             }
  1195.  
  1196.             // Add this address to our reservoirBuffer so we can free it later
  1197.  
  1198.             sAllocUnit    **temp = (sAllocUnit **) realloc(reservoirBuffer, (reservoirBufferSize + 1) * sizeof(sAllocUnit *));
  1199.             m_assert(temp);
  1200.             if (temp)
  1201.             {
  1202.                 reservoirBuffer = temp;
  1203.                 reservoirBuffer[reservoirBufferSize++] = reservoir;
  1204.             }
  1205.         }
  1206.  
  1207.         // Logical flow says this should never happen...
  1208.         m_assert(reservoir != NULL);
  1209.  
  1210.         // Grab a new allocaton unit from the front of the reservoir
  1211.  
  1212.         sAllocUnit    *au = reservoir;
  1213.         reservoir = au->next;
  1214.  
  1215.         // Populate it with some real data
  1216.  
  1217.         memset(au, 0, sizeof(sAllocUnit));
  1218.         au->actualSize        = calculateActualSize(reportedSize);
  1219.         #ifdef RANDOM_FAILURE
  1220.         double    a = rand();
  1221.         double    b = RAND_MAX / 100.0 * RANDOM_FAILURE;
  1222.         if (a > b)
  1223.         {
  1224.             au->actualAddress = malloc(au->actualSize);
  1225.         }
  1226.         else
  1227.         {
  1228.             log("[F] Random faiure");
  1229.             au->actualAddress = NULL;
  1230.         }
  1231.         #else
  1232.         au->actualAddress     = malloc(au->actualSize);
  1233.         #endif
  1234.         au->reportedSize      = reportedSize;
  1235.         au->reportedAddress   = calculateReportedAddress(au->actualAddress);
  1236.         au->allocationType    = allocationType;
  1237.         au->sourceLine        = sourceLine;
  1238.         au->allocationNumber  = currentAllocationCount;
  1239.         if (sourceFile) strncpy(au->sourceFile, sourceFileStripper(sourceFile), sizeof(au->sourceFile) - 1);
  1240.         else        strcpy (au->sourceFile, "??");
  1241.         if (sourceFunc) strncpy(au->sourceFunc, sourceFunc, sizeof(au->sourceFunc) - 1);
  1242.         else        strcpy (au->sourceFunc, "??");
  1243.  
  1244.         // We don't want to assert with random failures, because we want the application to deal with them.
  1245.  
  1246.         #ifndef RANDOM_FAILURE
  1247.         // If you hit this assert, then the requested allocation simply failed (you're out of memory.) Interrogate the
  1248.         // variable 'au' or the stack frame to see what you were trying to do.
  1249.         m_assert(au->actualAddress != NULL);
  1250.         #endif
  1251.  
  1252.         if (au->actualAddress == NULL)
  1253.         {
  1254.             throw "Request for allocation failed. Out of memory.";
  1255.         }
  1256.  
  1257.         // If you hit this assert, then this allocation was made from a source that isn't setup to use this memory tracking
  1258.         // software, use the stack frame to locate the source and include our H file.
  1259.         m_assert(allocationType != m_alloc_unknown);
  1260.  
  1261.         // Insert the new allocation into the hash table
  1262.  
  1263.         unsigned int    hashIndex = (reinterpret_cast<unsigned int>(au->reportedAddress) >> 4) & (hashSize - 1);
  1264.         if (hashTable[hashIndex]) hashTable[hashIndex]->prev = au;
  1265.         au->next = hashTable[hashIndex];
  1266.         au->prev = NULL;
  1267.         hashTable[hashIndex] = au;
  1268.  
  1269.         // Account for the new allocatin unit in our stats
  1270.  
  1271.         stats.totalReportedMemory += static_cast<unsigned int>(au->reportedSize);
  1272.         stats.totalActualMemory   += static_cast<unsigned int>(au->actualSize);
  1273.         stats.totalAllocUnitCount++;
  1274.         if (stats.totalReportedMemory > stats.peakReportedMemory) stats.peakReportedMemory = stats.totalReportedMemory;
  1275.         if (stats.totalActualMemory   > stats.peakActualMemory)   stats.peakActualMemory   = stats.totalActualMemory;
  1276.         if (stats.totalAllocUnitCount > stats.peakAllocUnitCount) stats.peakAllocUnitCount = stats.totalAllocUnitCount;
  1277.         stats.accumulatedReportedMemory += static_cast<unsigned int>(au->reportedSize);
  1278.         stats.accumulatedActualMemory += static_cast<unsigned int>(au->actualSize);
  1279.         stats.accumulatedAllocUnitCount++;
  1280.  
  1281.         // Prepare the allocation unit for use (wipe it with recognizable garbage)
  1282.  
  1283.         wipeWithPattern(au, unusedPattern);
  1284.  
  1285.         // calloc() expects the reported memory address range to be filled with 0's
  1286.  
  1287.         if (allocationType == m_alloc_calloc)
  1288.         {
  1289.             memset(au->reportedAddress, 0, au->reportedSize);
  1290.         }
  1291.  
  1292.         // Validate every single allocated unit in memory
  1293.  
  1294.         if (alwaysValidateAll) m_validateAllAllocUnits();
  1295.  
  1296.         // Log the result
  1297.  
  1298.         if (alwaysLogAll) log("[+] ---->             addr 0x%08X", reinterpret_cast<unsigned int>(au->reportedAddress));
  1299.  
  1300.         // Resetting the globals insures that if at some later time, somebody calls our memory manager from an unknown
  1301.         // source (i.e. they didn't include our H file) then we won't think it was the last allocation.
  1302.  
  1303.         resetGlobals();
  1304.  
  1305.         // Return the (reported) address of the new allocation unit
  1306.  
  1307.         #ifdef TEST_MEMORY_MANAGER
  1308.         log("[D] EXIT : m_allocator()");
  1309.         #endif
  1310.  
  1311.         return au->reportedAddress;
  1312.     }
  1313.     catch(const char *err)
  1314.     {
  1315.         // Deal with the errors
  1316.  
  1317.         log("[!] %s", err);
  1318.         resetGlobals();
  1319.  
  1320.         #ifdef TEST_MEMORY_MANAGER
  1321.         log("[D] EXIT : m_allocator()");
  1322.         #endif
  1323.  
  1324.         return NULL;
  1325.     }
  1326. }
  1327.  
  1328. // ---------------------------------------------------------------------------------------------------------------------------------
  1329. // Reallocate memory and track it
  1330. // ---------------------------------------------------------------------------------------------------------------------------------
  1331.  
  1332. void    *m_reallocator(const char *sourceFile, const unsigned int sourceLine, const char *sourceFunc, const unsigned int reallocationType, const size_t reportedSize, void *reportedAddress)
  1333. {
  1334.     LOCK
  1335.  
  1336.     try
  1337.     {
  1338.         #ifdef TEST_MEMORY_MANAGER
  1339.         log("[D] ENTER: m_reallocator()");
  1340.         #endif
  1341.  
  1342.         // Calling realloc with a NULL should force same operations as a malloc
  1343.  
  1344.         if (!reportedAddress)
  1345.         {
  1346.             return m_allocator(sourceFile, sourceLine, sourceFunc, reallocationType, reportedSize);
  1347.         }
  1348.  
  1349.         // Increase our allocation count
  1350.  
  1351.         currentAllocationCount++;
  1352.  
  1353.         // If you hit this assert, you requested a breakpoint on a specific allocation count
  1354.         m_assert(currentAllocationCount != breakOnAllocationCount);
  1355.  
  1356.         // Log the request
  1357.  
  1358.         if (alwaysLogAll) log("[~] %05d %8s of size 0x%08X(%08d) by %s", currentAllocationCount, allocationTypes[reallocationType], reportedSize, reportedSize, ownerString(sourceFile, sourceLine, sourceFunc));
  1359.  
  1360.         // Locate the existing allocation unit
  1361.  
  1362.         sAllocUnit    *au = findAllocUnit(reportedAddress);
  1363.  
  1364.         // If you hit this assert, you tried to reallocate RAM that wasn't allocated by this memory manager.
  1365.         m_assert(au != NULL);
  1366.         if (au == NULL) throw "Request to reallocate RAM that was never allocated";
  1367.  
  1368.         // If you hit this assert, then the allocation unit that is about to be reallocated is damaged. But you probably
  1369.         // already know that from a previous assert you should have seen in validateAllocUnit() :)
  1370.         m_assert(m_validateAllocUnit(au));
  1371.  
  1372.         // If you hit this assert, then this reallocation was made from a source that isn't setup to use this memory
  1373.         // tracking software, use the stack frame to locate the source and include our H file.
  1374.         m_assert(reallocationType != m_alloc_unknown);
  1375.  
  1376.         // If you hit this assert, you were trying to reallocate RAM that was not allocated in a way that is compatible with
  1377.         // realloc. In other words, you have a allocation/reallocation mismatch.
  1378.         m_assert(au->allocationType == m_alloc_malloc ||
  1379.              au->allocationType == m_alloc_calloc ||
  1380.              au->allocationType == m_alloc_realloc);
  1381.  
  1382.         // If you hit this assert, then the "break on realloc" flag for this allocation unit is set (and will continue to be
  1383.         // set until you specifically shut it off. Interrogate the 'au' variable to determine information about this
  1384.         // allocation unit.
  1385.         m_assert(au->breakOnRealloc == false);
  1386.  
  1387.         // Keep track of the original size
  1388.  
  1389.         unsigned int    originalReportedSize = static_cast<unsigned int>(au->reportedSize);
  1390.  
  1391.         if (alwaysLogAll) log("[~] ---->             from 0x%08X(%08d)", originalReportedSize, originalReportedSize);
  1392.  
  1393.         // Do the reallocation
  1394.  
  1395.         void    *oldReportedAddress = reportedAddress;
  1396.         size_t    newActualSize = calculateActualSize(reportedSize);
  1397.         void    *newActualAddress = NULL;
  1398.         #ifdef RANDOM_FAILURE
  1399.         double    a = rand();
  1400.         double    b = RAND_MAX / 100.0 * RANDOM_FAILURE;
  1401.         if (a > b)
  1402.         {
  1403.             newActualAddress = realloc(au->actualAddress, newActualSize);
  1404.         }
  1405.         else
  1406.         {
  1407.             log("[F] Random faiure");
  1408.         }
  1409.         #else
  1410.         newActualAddress = realloc(au->actualAddress, newActualSize);
  1411.         #endif
  1412.  
  1413.         // We don't want to assert with random failures, because we want the application to deal with them.
  1414.  
  1415.         #ifndef RANDOM_FAILURE
  1416.         // If you hit this assert, then the requested allocation simply failed (you're out of memory) Interrogate the
  1417.         // variable 'au' to see the original allocation. You can also query 'newActualSize' to see the amount of memory
  1418.         // trying to be allocated. Finally, you can query 'reportedSize' to see how much memory was requested by the caller.
  1419.         m_assert(newActualAddress);
  1420.         #endif
  1421.  
  1422.         if (!newActualAddress) throw "Request for reallocation failed. Out of memory.";
  1423.  
  1424.         // Remove this allocation from our stats (we'll add the new reallocation again later)
  1425.  
  1426.         stats.totalReportedMemory -= static_cast<unsigned int>(au->reportedSize);
  1427.         stats.totalActualMemory   -= static_cast<unsigned int>(au->actualSize);
  1428.  
  1429.         // Update the allocation with the new information
  1430.  
  1431.         au->actualSize        = newActualSize;
  1432.         au->actualAddress     = newActualAddress;
  1433.         au->reportedSize      = calculateReportedSize(newActualSize);
  1434.         au->reportedAddress   = calculateReportedAddress(newActualAddress);
  1435.         au->allocationType    = reallocationType;
  1436.         au->sourceLine        = sourceLine;
  1437.         au->allocationNumber  = currentAllocationCount;
  1438.         if (sourceFile) strncpy(au->sourceFile, sourceFileStripper(sourceFile), sizeof(au->sourceFile) - 1);
  1439.         else        strcpy (au->sourceFile, "??");
  1440.         if (sourceFunc) strncpy(au->sourceFunc, sourceFunc, sizeof(au->sourceFunc) - 1);
  1441.         else        strcpy (au->sourceFunc, "??");
  1442.  
  1443.         // The reallocation may cause the address to change, so we should relocate our allocation unit within the hash table
  1444.  
  1445.         unsigned int    hashIndex = static_cast<unsigned int>(-1);
  1446.         if (oldReportedAddress != au->reportedAddress)
  1447.         {
  1448.             // Remove this allocation unit from the hash table
  1449.  
  1450.             {
  1451.                 unsigned int    hashIndex = (reinterpret_cast<unsigned int>(oldReportedAddress) >> 4) & (hashSize - 1);
  1452.                 if (hashTable[hashIndex] == au)
  1453.                 {
  1454.                     hashTable[hashIndex] = hashTable[hashIndex]->next;
  1455.                 }
  1456.                 else
  1457.                 {
  1458.                     if (au->prev)    au->prev->next = au->next;
  1459.                     if (au->next)    au->next->prev = au->prev;
  1460.                 }
  1461.             }
  1462.  
  1463.             // Re-insert it back into the hash table
  1464.  
  1465.             hashIndex = (reinterpret_cast<unsigned int>(au->reportedAddress) >> 4) & (hashSize - 1);
  1466.             if (hashTable[hashIndex]) hashTable[hashIndex]->prev = au;
  1467.             au->next = hashTable[hashIndex];
  1468.             au->prev = NULL;
  1469.             hashTable[hashIndex] = au;
  1470.         }
  1471.  
  1472.         // Account for the new allocatin unit in our stats
  1473.  
  1474.         stats.totalReportedMemory += static_cast<unsigned int>(au->reportedSize);
  1475.         stats.totalActualMemory   += static_cast<unsigned int>(au->actualSize);
  1476.         if (stats.totalReportedMemory > stats.peakReportedMemory) stats.peakReportedMemory = stats.totalReportedMemory;
  1477.         if (stats.totalActualMemory   > stats.peakActualMemory)   stats.peakActualMemory   = stats.totalActualMemory;
  1478.         int    deltaReportedSize = static_cast<int>(reportedSize - originalReportedSize);
  1479.         if (deltaReportedSize > 0)
  1480.         {
  1481.             stats.accumulatedReportedMemory += deltaReportedSize;
  1482.             stats.accumulatedActualMemory += deltaReportedSize;
  1483.         }
  1484.  
  1485.         // Prepare the allocation unit for use (wipe it with recognizable garbage)
  1486.  
  1487.         wipeWithPattern(au, unusedPattern, originalReportedSize);
  1488.  
  1489.         // If you hit this assert, then something went wrong, because the allocation unit was properly validated PRIOR to
  1490.         // the reallocation. This should not happen.
  1491.         m_assert(m_validateAllocUnit(au));
  1492.  
  1493.         // Validate every single allocated unit in memory
  1494.  
  1495.         if (alwaysValidateAll) m_validateAllAllocUnits();
  1496.  
  1497.         // Log the result
  1498.  
  1499.         if (alwaysLogAll) log("[~] ---->             addr 0x%08X", reinterpret_cast<unsigned int>(au->reportedAddress));
  1500.  
  1501.         // Resetting the globals insures that if at some later time, somebody calls our memory manager from an unknown
  1502.         // source (i.e. they didn't include our H file) then we won't think it was the last allocation.
  1503.  
  1504.         resetGlobals();
  1505.  
  1506.         // Return the (reported) address of the new allocation unit
  1507.  
  1508.         #ifdef TEST_MEMORY_MANAGER
  1509.         log("[D] EXIT : m_reallocator()");
  1510.         #endif
  1511.  
  1512.         return au->reportedAddress;
  1513.     }
  1514.     catch(const char *err)
  1515.     {
  1516.         // Deal with the errors
  1517.  
  1518.         log("[!] %s", err);
  1519.         resetGlobals();
  1520.  
  1521.         #ifdef TEST_MEMORY_MANAGER
  1522.         log("[D] EXIT : m_reallocator()");
  1523.         #endif
  1524.  
  1525.         return NULL;
  1526.     }
  1527. }
  1528.  
  1529. // ---------------------------------------------------------------------------------------------------------------------------------
  1530. // Deallocate memory and track it
  1531. // ---------------------------------------------------------------------------------------------------------------------------------
  1532.  
  1533. void    m_deallocator(const char *sourceFile, const unsigned int sourceLine, const char *sourceFunc, const unsigned int deallocationType, const void *reportedAddress)
  1534. {
  1535.     LOCK
  1536.  
  1537.     try
  1538.     {
  1539.         #ifdef TEST_MEMORY_MANAGER
  1540.         log("[D] ENTER: m_deallocator()");
  1541.         #endif
  1542.  
  1543.         // Log the request
  1544.  
  1545.         if (alwaysLogAll) log("[-] ----- %8s of addr 0x%08X           by %s", allocationTypes[deallocationType], reinterpret_cast<unsigned int>(const_cast<void *>(reportedAddress)), ownerString(sourceFile, sourceLine, sourceFunc));
  1546.  
  1547.         // We should only ever get here with a null pointer if they try to do so with a call to free() (delete[] and delete will
  1548.         // both bail before they get here.) So, since ANSI allows free(NULL), we'll not bother trying to actually free the allocated
  1549.         // memory or track it any further.
  1550.  
  1551.         if (reportedAddress)
  1552.         {
  1553.             // Go get the allocation unit
  1554.  
  1555.             sAllocUnit    *au = findAllocUnit(reportedAddress);
  1556.  
  1557.             // If you hit this assert, you tried to deallocate RAM that wasn't allocated by this memory manager.
  1558.             m_assert(au != NULL);
  1559.             if (au == NULL) throw "Request to deallocate RAM that was never allocated";
  1560.  
  1561.             // If you hit this assert, then the allocation unit that is about to be deallocated is damaged. But you probably
  1562.             // already know that from a previous assert you should have seen in validateAllocUnit() :)
  1563.             m_assert(m_validateAllocUnit(au));
  1564.  
  1565.             // If you hit this assert, then this deallocation was made from a source that isn't setup to use this memory
  1566.             // tracking software, use the stack frame to locate the source and include our H file.
  1567.             m_assert(deallocationType != m_alloc_unknown);
  1568.  
  1569.             // If you hit this assert, you were trying to deallocate RAM that was not allocated in a way that is compatible with
  1570.             // the deallocation method requested. In other words, you have a allocation/deallocation mismatch.
  1571.             m_assert((deallocationType == m_alloc_delete       && au->allocationType == m_alloc_new      ) ||
  1572.                 (deallocationType == m_alloc_delete_array && au->allocationType == m_alloc_new_array) ||
  1573.                 (deallocationType == m_alloc_free         && au->allocationType == m_alloc_malloc   ) ||
  1574.                 (deallocationType == m_alloc_free         && au->allocationType == m_alloc_calloc   ) ||
  1575.                 (deallocationType == m_alloc_free         && au->allocationType == m_alloc_realloc  ) ||
  1576.                 (deallocationType == m_alloc_unknown                                                ) );
  1577.  
  1578.             // If you hit this assert, then the "break on dealloc" flag for this allocation unit is set. Interrogate the 'au'
  1579.             // variable to determine information about this allocation unit.
  1580.             m_assert(au->breakOnDealloc == false);
  1581.  
  1582.             // Wipe the deallocated RAM with a new pattern. This doen't actually do us much good in debug mode under WIN32,
  1583.             // because Microsoft's memory debugging & tracking utilities will wipe it right after we do. Oh well.
  1584.  
  1585.             wipeWithPattern(au, releasedPattern);
  1586.  
  1587.             // Do the deallocation
  1588.  
  1589.             free(au->actualAddress);
  1590.  
  1591.             // Remove this allocation unit from the hash table
  1592.  
  1593.             unsigned int    hashIndex = (reinterpret_cast<unsigned int>(au->reportedAddress) >> 4) & (hashSize - 1);
  1594.             if (hashTable[hashIndex] == au)
  1595.             {
  1596.                 hashTable[hashIndex] = au->next;
  1597.             }
  1598.             else
  1599.             {
  1600.                 if (au->prev)    au->prev->next = au->next;
  1601.                 if (au->next)    au->next->prev = au->prev;
  1602.             }
  1603.  
  1604.             // Remove this allocation from our stats
  1605.  
  1606.             stats.totalReportedMemory -= static_cast<unsigned int>(au->reportedSize);
  1607.             stats.totalActualMemory   -= static_cast<unsigned int>(au->actualSize);
  1608.             stats.totalAllocUnitCount--;
  1609.  
  1610.             // Add this allocation unit to the front of our reservoir of unused allocation units
  1611.  
  1612.             memset(au, 0, sizeof(sAllocUnit));
  1613.             au->next = reservoir;
  1614.             reservoir = au;
  1615.         }
  1616.  
  1617.         // Resetting the globals insures that if at some later time, somebody calls our memory manager from an unknown
  1618.         // source (i.e. they didn't include our H file) then we won't think it was the last allocation.
  1619.  
  1620.         resetGlobals();
  1621.  
  1622.         // Validate every single allocated unit in memory
  1623.  
  1624.         if (alwaysValidateAll) m_validateAllAllocUnits();
  1625.  
  1626.         // If we're in the midst of static deinitialization time, track any pending memory leaks
  1627.  
  1628.         if (staticDeinitTime) dumpLeakReport();
  1629.     }
  1630.     catch(const char *err)
  1631.     {
  1632.         // Deal with errors
  1633.  
  1634.         log("[!] %s", err);
  1635.         resetGlobals();
  1636.     }
  1637.  
  1638.     #ifdef TEST_MEMORY_MANAGER
  1639.     log("[D] EXIT : m_deallocator()");
  1640.     #endif
  1641. }
  1642.  
  1643. // ---------------------------------------------------------------------------------------------------------------------------------
  1644. // -DOC- The following utilitarian allow you to become proactive in tracking your own memory, or help you narrow in on those tough
  1645. // bugs.
  1646. // ---------------------------------------------------------------------------------------------------------------------------------
  1647.  
  1648. bool    m_validateAddress(const void *reportedAddress)
  1649. {
  1650.     LOCK
  1651.  
  1652.     // Just see if the address exists in our allocation routines
  1653.  
  1654.     return findAllocUnit(reportedAddress) != NULL;
  1655. }
  1656.  
  1657. // ---------------------------------------------------------------------------------------------------------------------------------
  1658.  
  1659. bool    m_validateAllocUnit(const sAllocUnit *allocUnit)
  1660. {
  1661.     LOCK
  1662.  
  1663.     // Make sure the padding is untouched
  1664.  
  1665.     long    *pre = reinterpret_cast<long *>(allocUnit->actualAddress);
  1666.     long    *post = reinterpret_cast<long *>((char *)allocUnit->actualAddress + allocUnit->actualSize - paddingSize * sizeof(long));
  1667.     bool    errorFlag = false;
  1668.     for (unsigned int i = 0; i < paddingSize; i++, pre++, post++)
  1669.     {
  1670.         if (*pre != (long) prefixPattern)
  1671.         {
  1672.             log("[!] A memory allocation unit was corrupt because of an underrun:");
  1673.             m_dumpAllocUnit(allocUnit, "  ");
  1674.             errorFlag = true;
  1675.         }
  1676.  
  1677.         // If you hit this assert, then you should know that this allocation unit has been damaged. Something (possibly the
  1678.         // owner?) has underrun the allocation unit (modified a few bytes prior to the start). You can interrogate the
  1679.         // variable 'allocUnit' to see statistics and information about this damaged allocation unit.
  1680.         m_assert(*pre == static_cast<long>(prefixPattern));
  1681.  
  1682.         if (*post != static_cast<long>(postfixPattern))
  1683.         {
  1684.             log("[!] A memory allocation unit was corrupt because of an overrun:");
  1685.             m_dumpAllocUnit(allocUnit, "  ");
  1686.             errorFlag = true;
  1687.         }
  1688.  
  1689.         // If you hit this assert, then you should know that this allocation unit has been damaged. Something (possibly the
  1690.         // owner?) has overrun the allocation unit (modified a few bytes after the end). You can interrogate the variable
  1691.         // 'allocUnit' to see statistics and information about this damaged allocation unit.
  1692.         m_assert(*post == static_cast<long>(postfixPattern));
  1693.     }
  1694.  
  1695.     // Return the error status (we invert it, because a return of 'false' means error)
  1696.  
  1697.     return !errorFlag;
  1698. }
  1699.  
  1700. // ---------------------------------------------------------------------------------------------------------------------------------
  1701.  
  1702. bool    m_validateAllAllocUnits()
  1703. {
  1704.     LOCK
  1705.  
  1706.     // Just go through each allocation unit in the hash table and count the ones that have errors
  1707.  
  1708.     unsigned int    errors = 0;
  1709.     unsigned int    allocCount = 0;
  1710.     for (unsigned int i = 0; i < hashSize; i++)
  1711.     {
  1712.         sAllocUnit    *ptr = hashTable[i];
  1713.         while(ptr)
  1714.         {
  1715.             allocCount++;
  1716.             if (!m_validateAllocUnit(ptr)) errors++;
  1717.             ptr = ptr->next;
  1718.         }
  1719.     }
  1720.  
  1721.     // Test for hash-table correctness
  1722.  
  1723.     if (allocCount != stats.totalAllocUnitCount)
  1724.     {
  1725.         log("[!] Memory tracking hash table corrupt!");
  1726.         errors++;
  1727.     }
  1728.  
  1729.     // If you hit this assert, then the internal memory (hash table) used by this memory tracking software is damaged! The
  1730.     // best way to track this down is to use the alwaysLogAll flag in conjunction with STRESS_TEST macro to narrow in on the
  1731.     // offending code. After running the application with these settings (and hitting this assert again), interrogate the
  1732.     // memory.log file to find the previous successful operation. The corruption will have occurred between that point and this
  1733.     // assertion.
  1734.     m_assert(allocCount == stats.totalAllocUnitCount);
  1735.  
  1736.     // If you hit this assert, then you've probably already been notified that there was a problem with a allocation unit in a
  1737.     // prior call to validateAllocUnit(), but this assert is here just to make sure you know about it. :)
  1738.     m_assert(errors == 0);
  1739.  
  1740.     // Log any errors
  1741.  
  1742.     if (errors) log("[!] While validting all allocation units, %d allocation unit(s) were found to have problems", errors);
  1743.  
  1744.     // Return the error status
  1745.  
  1746.     return errors != 0;
  1747. }
  1748.  
  1749. // ---------------------------------------------------------------------------------------------------------------------------------
  1750. // -DOC- Unused RAM calculation routines. Use these to determine how much of your RAM is unused (in bytes)
  1751. // ---------------------------------------------------------------------------------------------------------------------------------
  1752.  
  1753. unsigned int    m_calcUnused(const sAllocUnit *allocUnit)
  1754. {
  1755.     LOCK
  1756.  
  1757.     const unsigned long    *ptr = reinterpret_cast<const unsigned long *>(allocUnit->reportedAddress);
  1758.     unsigned int        count = 0;
  1759.  
  1760.     for (unsigned int i = 0; i < allocUnit->reportedSize; i += sizeof(long), ptr++)
  1761.     {
  1762.         if (*ptr == unusedPattern) count += sizeof(long);
  1763.     }
  1764.  
  1765.     return count;
  1766. }
  1767.  
  1768. // ---------------------------------------------------------------------------------------------------------------------------------
  1769.  
  1770. unsigned int    m_calcAllUnused()
  1771. {
  1772.     LOCK
  1773.  
  1774.     // Just go through each allocation unit in the hash table and count the unused RAM
  1775.  
  1776.     unsigned int    total = 0;
  1777.     for (unsigned int i = 0; i < hashSize; i++)
  1778.     {
  1779.         sAllocUnit    *ptr = hashTable[i];
  1780.         while(ptr)
  1781.         {
  1782.             total += m_calcUnused(ptr);
  1783.             ptr = ptr->next;
  1784.         }
  1785.     }
  1786.  
  1787.     return total;
  1788. }
  1789.  
  1790. // ---------------------------------------------------------------------------------------------------------------------------------
  1791. // -DOC- The following functions are for logging and statistics reporting.
  1792. // ---------------------------------------------------------------------------------------------------------------------------------
  1793.  
  1794. void    m_dumpAllocUnit(const sAllocUnit *allocUnit, const char *prefix)
  1795. {
  1796.     LOCK
  1797.  
  1798.     log("[I] %sAddress (reported): %010p",       prefix, allocUnit->reportedAddress);
  1799.     log("[I] %sAddress (actual)  : %010p",       prefix, allocUnit->actualAddress);
  1800.     log("[I] %sSize (reported)   : 0x%08X (%s)", prefix, static_cast<unsigned int>(allocUnit->reportedSize), memorySizeString(static_cast<unsigned int>(allocUnit->reportedSize)));
  1801.     log("[I] %sSize (actual)     : 0x%08X (%s)", prefix, static_cast<unsigned int>(allocUnit->actualSize), memorySizeString(static_cast<unsigned int>(allocUnit->actualSize)));
  1802.     log("[I] %sOwner             : %s(%d)::%s",  prefix, allocUnit->sourceFile, allocUnit->sourceLine, allocUnit->sourceFunc);
  1803.     log("[I] %sAllocation type   : %s",          prefix, allocationTypes[allocUnit->allocationType]);
  1804.     log("[I] %sAllocation number : %d",          prefix, allocUnit->allocationNumber);
  1805. }
  1806.  
  1807. // ---------------------------------------------------------------------------------------------------------------------------------
  1808.  
  1809. void    m_dumpMemoryReport(const char *filename, const bool overwrite)
  1810. {
  1811.     LOCK
  1812.  
  1813.     // Open the report file
  1814.  
  1815.     FILE    *fp = NULL;
  1816.     
  1817.     if (overwrite)    fp = fopen(filename, "w+b");
  1818.     else        fp = fopen(filename, "ab");
  1819.  
  1820.     // If you hit this assert, then the memory report generator is unable to log information to a file (can't open the file for
  1821.     // some reason.)
  1822.     m_assert(fp);
  1823.     if (!fp) return;
  1824.  
  1825.         // Header
  1826.  
  1827.         static  char    timeString[25];
  1828.         memset(timeString, 0, sizeof(timeString));
  1829.         time_t  t = time(NULL);
  1830.         struct  tm *tme = localtime(&t);
  1831.     fprintf(fp, " ---------------------------------------------------------------------------------------------------------------------------------- \r\n");
  1832.         fprintf(fp, "|                                             Memory report for: %02d/%02d/%04d %02d:%02d:%02d                                               |\r\n", tme->tm_mon + 1, tme->tm_mday, tme->tm_year + 1900, tme->tm_hour, tme->tm_min, tme->tm_sec);
  1833.     fprintf(fp, " ---------------------------------------------------------------------------------------------------------------------------------- \r\n");
  1834.     fprintf(fp, "\r\n");
  1835.     fprintf(fp, "\r\n");
  1836.  
  1837.     // Report summary
  1838.  
  1839.     fprintf(fp, " ---------------------------------------------------------------------------------------------------------------------------------- \r\n");
  1840.     fprintf(fp, "|                                                           T O T A L S                                                            |\r\n");
  1841.     fprintf(fp, " ---------------------------------------------------------------------------------------------------------------------------------- \r\n");
  1842.     fprintf(fp, "              Allocation unit count: %10s\r\n", insertCommas(stats.totalAllocUnitCount));
  1843.     fprintf(fp, "            Reported to application: %s\r\n", memorySizeString(stats.totalReportedMemory));
  1844.     fprintf(fp, "         Actual total memory in use: %s\r\n", memorySizeString(stats.totalActualMemory));
  1845.     fprintf(fp, "           Memory tracking overhead: %s\r\n", memorySizeString(stats.totalActualMemory - stats.totalReportedMemory));
  1846.     fprintf(fp, "\r\n");
  1847.  
  1848.     fprintf(fp, " ---------------------------------------------------------------------------------------------------------------------------------- \r\n");
  1849.     fprintf(fp, "|                                                            P E A K S                                                             |\r\n");
  1850.     fprintf(fp, " ---------------------------------------------------------------------------------------------------------------------------------- \r\n");
  1851.     fprintf(fp, "              Allocation unit count: %10s\r\n", insertCommas(stats.peakAllocUnitCount));
  1852.     fprintf(fp, "            Reported to application: %s\r\n", memorySizeString(stats.peakReportedMemory));
  1853.     fprintf(fp, "                             Actual: %s\r\n", memorySizeString(stats.peakActualMemory));
  1854.     fprintf(fp, "           Memory tracking overhead: %s\r\n", memorySizeString(stats.peakActualMemory - stats.peakReportedMemory));
  1855.     fprintf(fp, "\r\n");
  1856.  
  1857.     fprintf(fp, " ---------------------------------------------------------------------------------------------------------------------------------- \r\n");
  1858.     fprintf(fp, "|                                                      A C C U M U L A T E D                                                       |\r\n");
  1859.     fprintf(fp, " ---------------------------------------------------------------------------------------------------------------------------------- \r\n");
  1860.     fprintf(fp, "              Allocation unit count: %s\r\n", memorySizeString(stats.accumulatedAllocUnitCount));
  1861.     fprintf(fp, "            Reported to application: %s\r\n", memorySizeString(stats.accumulatedReportedMemory));
  1862.     fprintf(fp, "                             Actual: %s\r\n", memorySizeString(stats.accumulatedActualMemory));
  1863.     fprintf(fp, "\r\n");
  1864.  
  1865.     fprintf(fp, " ---------------------------------------------------------------------------------------------------------------------------------- \r\n");
  1866.     fprintf(fp, "|                                                           U N U S E D                                                            |\r\n");
  1867.     fprintf(fp, " ---------------------------------------------------------------------------------------------------------------------------------- \r\n");
  1868.     fprintf(fp, "    Memory allocated but not in use: %s\r\n", memorySizeString(m_calcAllUnused()));
  1869.     fprintf(fp, "\r\n");
  1870.  
  1871.     dumpAllocations(fp);
  1872.  
  1873.     fclose(fp);
  1874. }
  1875.  
  1876. // ---------------------------------------------------------------------------------------------------------------------------------
  1877.  
  1878. sMStats    m_getMemoryStatistics()
  1879. {
  1880.     return stats;
  1881. }
  1882.  
  1883. // ---------------------------------------------------------------------------------------------------------------------------------
  1884. // mmgr.cpp - End of file
  1885. // ---------------------------------------------------------------------------------------------------------------------------------
  1886.  
  1887. #endif